package org.xhy.hrm.service.impl;

import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.xhy.hrm.asserts.GlobleAssert;
import org.xhy.hrm.client.LoginUserClient;
import org.xhy.hrm.domain.Employee;
import org.xhy.hrm.domain.LoginUser;
import org.xhy.hrm.domain.Tenant;
import org.xhy.hrm.dto.TenantEnteringDto;
import org.xhy.hrm.globle.GlobleException;
import org.xhy.hrm.mapper.EmployeeMapper;
import org.xhy.hrm.mapper.TenantMapper;
import org.xhy.hrm.query.TenantQuery;
import org.xhy.hrm.service.ITenantService;
import org.xhy.hrm.util.AjaxResult;
import org.xhy.hrm.util.PageList;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xhy
 * @since 2021-09-11
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements ITenantService {

    @Autowired
    private TenantMapper tenantMapper;

    @Autowired
    private LoginUserClient loginUserClient;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public PageList<Tenant> selectPageList(TenantQuery query) {
        //分页条件
        Page<Tenant> page = new Page<Tenant>(query.getPage(),query.getRows());
        //关联查询的结构
        List<Tenant> datas = tenantMapper.loadPageList(page,query);
        return new PageList<>(page.getTotal(),datas);
    }

    @Transactional
    @Override
    public void entering(TenantEnteringDto dto) {

       /* GlobleAssert.hasText(dto.getTenant().getCompanyName(),"公司名不能为空");
        GlobleAssert.isPhone(dto.getTenant().getAdmin().getTel(),"请输入正确手机号");
        GlobleAssert.isEmail(dto.getTenant().getAdmin().getEmail(),"请输入正确邮箱号");*/

        //抽取
        Employee employee = dto.getEmployee();
        Tenant tenant = dto.getTenant();
        //保存loginUser
        LoginUser loginUser = new LoginUser();
        loginUser.setUsername(employee.getUsername());
        loginUser.setPassword(employee.getPassword());
        //0：管理员 1：用户
        loginUser.setType(1);
        AjaxResult ajaxResult = loginUserClient.addOrUpdate(loginUser);
        if (!ajaxResult.isSuccess()){
            throw new RuntimeException("报错了");
        }
        Long loginId = Long.valueOf(ajaxResult.getResultObj().toString());
        System.out.println(loginId);

        //保存管理员
        employee.setLoginId(loginId);
        employeeMapper.insert(employee);

        //保存租户
        tenant.setAdminId(employee.getId());
        tenantMapper.insert(tenant);

        //保存租户和套餐中间表
        Long tenantId = tenant.getId();
        Long mealId = dto.getMealId();
        tenantMapper.saveTenantMeal(tenantId,mealId);
    }
}
